package org.tinygroup.bizframe.common.util;

import java.math.BigInteger;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.beanutils.Converter;
import org.apache.commons.beanutils.converters.BigDecimalConverter;
import org.apache.commons.beanutils.converters.BigIntegerConverter;
import org.apache.commons.beanutils.converters.DoubleConverter;
import org.apache.commons.beanutils.converters.FloatConverter;
import org.apache.commons.beanutils.converters.IntegerConverter;
import org.apache.commons.beanutils.converters.LongConverter;
import org.apache.commons.beanutils.converters.ShortConverter;
import org.springframework.beans.factory.InitializingBean;
import org.tinygroup.logger.Logger;
import org.tinygroup.logger.LoggerFactory;


public class DateConvert implements Converter,InitializingBean {
    private static final Logger logger = LoggerFactory.getLogger(DateConvert.class);
	public Date convert(Class type, Object value) {
		logger.warnMessage("date convert,calss:{}-->val:{}", type.getName(),value);
		if(value==null){
			return null;
		}
		if(value instanceof Date ){
			return (Date)value;
		}
		if(value instanceof String ){
			String p = (String)value;
			if(p== null || p.trim().length()==0){
	            return null;
	        }   
			try{
	            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	            return df.parse(p.trim());
	        }
	        catch(Exception e){
	            try {
	                SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
	                return df.parse(p.trim());
	            } catch (ParseException ex) {
	                return null;
	            }
	        }
		}
		if(value instanceof Long){
			return new Date((Long)value);
		}
		return null;
	}

	@Override
	public void afterPropertiesSet() throws Exception {
		
		logger.warnMessage("register date convert-----------");
		ConvertUtils.register(new IntegerConverter(null), Integer.TYPE);
		ConvertUtils.register(new IntegerConverter(null), Integer.class);
		
		ConvertUtils.register(new LongConverter(null), Long.TYPE);
		ConvertUtils.register(new LongConverter(null), Long.class);
		
		ConvertUtils.register(new FloatConverter(null), Float.TYPE);
		ConvertUtils.register(new FloatConverter(null), Float.class);
		
		ConvertUtils.register(new DoubleConverter(null), DoubleConverter.class);
		
		ConvertUtils.register(new ShortConverter(null), ShortConverter.class);
		
		ConvertUtils.register(new BigIntegerConverter(null), BigIntegerConverter.class);
		ConvertUtils.register(new BigDecimalConverter(null), BigDecimalConverter.class);
		
		ConvertUtils.register(this, Date.class);
	}
}
